import axios from 'axios'
import { Toast } from 'vant'
import Router from '@/router'
axios.defaults.baseURL = process.env.VUE_APP_API + '/etc-unified-platform/platform/invoiceService/v1'


// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  Toast.loading('加载中...')
  return config;
}, function (error) {
  // 对请求错误做些什么
  Toast.hide()
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  Toast.clear()
  if (response.data.resultCode == 0) {
    return response.data
  } else if (response.data.resultCode == 733) {
    Router.push({ name: 'Login' })
    localStorage.removeItem('ticketId')
    localStorage.removeItem('mobile')
    Toast.fail('登录已失效，请重新登录！')
    return response
  }
  else {
    Toast.fail(response.data.description)
    return response
  }



  // return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});


function formatData(data) {
  let appId = location.search ? location.search.split('=')[1] : '10001'
  let timestamp = (new Date()).getTime()
  let ticketId = localStorage.getItem('ticketId')
  let baseData = {
    "appId": appId,
    "timestamp": timestamp,
    "data": {
      ...data
    },
  }
  if (ticketId) { baseData.data.ticketId = ticketId }
  return Object.assign(baseData, {
    
  })
}


/**
 * 7 鉴权
 */

// 7.1 获取短信验证码
export const getValidCode = params => {
  return axios.post('/authLogin/getValidCode', formatData(params)).then(res => res.data)
}

/zzzz